package cn.kailangtu.dataspot.activify;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.LinkedBlockingQueue;

import cn.kailangtu.commontools.APPSPUtils;
import cn.kailangtu.commontools.AdbUtil;
import cn.kailangtu.commontools.AppUtils;
import cn.kailangtu.commontools.CommonUtils;
import cn.kailangtu.dataspot.MainActivity;
import cn.kailangtu.dataspot.MainLowActivity;
import cn.kailangtu.dataspot.NtpClientWithLib;
import cn.kailangtu.dataspot.R;
import cn.kailangtu.serialutils.api.Com1;
import cn.kailangtu.serialutils.api.Com2;
import cn.kailangtu.serialutils.api.Com3;
import cn.kailangtu.serialutils.api.Com4;
import cn.kailangtu.serialutils.api.Com5;
import cn.kailangtu.serialutils.api.DIManager;
import cn.kailangtu.serialutils.api.DIMessageListener;
import cn.kailangtu.serialutils.api.InfraredManager;
import cn.kailangtu.serialutils.api.InfraredMessageListener;
import cn.kailangtu.serialutils.api.ReceiveMsgListenerV2;
import cn.kailangtu.serialutils.modbus.modbusUtil;

public class SplashActivity extends AppCompatActivity {


    private LinkedBlockingQueue<String> msgQueue = new LinkedBlockingQueue<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_splash);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
         AppUtils.getInstance().hideButton(this);


        new Thread(new Runnable() {
            @Override
            public void run() {

                boolean isOk = false;
                while(!isOk) {
                    try {
                        Date ntpTime = NtpClientWithLib.getNtpTime();
                        Date locaData = new Date();
                        isOk = true;
                        if (ntpTime.getTime() - locaData.getTime() > 1000 * 60 * 60) {
                            //System.out.println("NTP 时间: " + ntpTime);
                            Log.d("SHOOTLEEE", "NTP 时间: " + ntpTime);

                            SimpleDateFormat format = new SimpleDateFormat("MMddHHmmyyyy.ss", Locale.getDefault());
                            String timeStr = format.format(ntpTime.getTime());
                            Log.d("TIMETIMETIME", timeStr);
                            AdbUtil.run("date '" + timeStr + "'");
                            SystemClock.sleep(1000);
                              android.os.Process.killProcess(android.os.Process.myPid());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.d("SHOOTLEEE", "NTP 时间,ERR: " + e.getMessage());
                    }
                    SystemClock.sleep(1000);
                }
            }
        }).start();


        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) LinearLayout ll = (LinearLayout) findViewById(R.id.llSerialPortSetting);
        if(ll.getVisibility() != View.VISIBLE) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    SystemClock.sleep(3000);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (APPSPUtils.getInstance().getLastMainPage() == 2) {
                                startActivity(new Intent(SplashActivity.this, MainLowActivity.class));
                            } else {
                                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                            }
                            SplashActivity.this.finish();
                        }
                    });
                }
            }).start();
        }
        else {
            DIManager.getInstance().initListener(new DIMessageListener() {
                @Override
                public void onReceiveAction(int itemNo, int actionCode, String actionMsg) {
                    String msg = "操作项:" + itemNo + "||值：" + actionCode + "||说明：" + actionMsg;
                    msgQueue.offer(msg);
                }
            });

            InfraredManager.getInstance().initListener(new InfraredMessageListener() {
                @Override
                public void onReceiveAction(int itemNo, int actionCode, String actionMsg) {
                    String msg = "操作项:" + itemNo + "||值：" + actionCode + "||说明：" + actionMsg;
                    msgQueue.offer(msg);
                }
            });
        }


       hide();

    }


    @Override
    public void onResume()
    {
        //隐藏虚拟按键，并且全屏
        super.onResume();
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }

        getWindow().setStatusBarColor(Color.TRANSPARENT);// Color.TRANSPARENT = 0 表示#00000000即透明颜色
        getWindow().setNavigationBarColor(Color.TRANSPARENT);

        //隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        TextView tvTitle = findViewById(R.id.tvSplashTitle);
       // tvTitle.setText("智能移变高压侧");
    }

    String TAG = "COM SETTING";
    public void openCom1(View view) {
        if(Com1.getInstance().isOpen())
        {
            Com1.getInstance().close();
            ((Button)view).setText("打开串口1");
        }
        else {
            Com1.getInstance().openSerialPort("/dev/ttys1", 9600, 0, new ReceiveMsgListenerV2() {
                @Override
                public void onReceiveData(byte[] data) {
                    Log.d(TAG, "COM1 receive:" + CommonUtils.ByteArrayToHexString(data));
                    msgQueue.offer("COM1 receive:" + CommonUtils.ByteArrayToHexString(data));
                }
            });
            if(Com1.getInstance().isOpen())
            {
                ((Button)view).setText("关闭串口1");
            }
        }

    }

    public void openCom5(View view) {
        if(Com5.getInstance().isOpen())
        {
            Com5.getInstance().close();
            ((Button)view).setText("打开串口5");
        }
        else {
            Com5.getInstance().openSerialPort("/dev/ttys5", 9600, 0, new ReceiveMsgListenerV2() {
                @Override
                public void onReceiveData(byte[] data) {
                    Log.d(TAG, "COM5 receive:" + CommonUtils.ByteArrayToHexString(data));
                    msgQueue.offer("COM5 receive:" + CommonUtils.ByteArrayToHexString(data));
                }
            });
            if(Com5.getInstance().isOpen())
            {
                ((Button)view).setText("关闭串口5");
            }
        }
    }

    public void openCom4(View view) {
        if(Com4.getInstance().isOpen())
        {
            Com4.getInstance().close();
            ((Button)view).setText("打开串口4");
        }
        else {
            Com4.getInstance().openSerialPort("/dev/ttys4", 9600, 0, new ReceiveMsgListenerV2() {
                @Override
                public void onReceiveData(byte[] data) {
                    Log.d(TAG, "COM4 receive:" + CommonUtils.ByteArrayToHexString(data));
                    msgQueue.offer("COM4 receive:" + CommonUtils.ByteArrayToHexString(data));
                }
            });
            if(Com4.getInstance().isOpen())
            {
                ((Button)view).setText("关闭串口4");
            }
        }
    }

    public void openCom3(View view) {
        if(Com3.getInstance().isOpen())
        {
            Com3.getInstance().close();
            ((Button)view).setText("打开串口3");
        }
        else {
            Com3.getInstance().openSerialPort("/dev/ttys3", 9600, 0, new ReceiveMsgListenerV2() {
                @Override
                public void onReceiveData(byte[] data) {
                    Log.d(TAG, "COM3 receive:" + CommonUtils.ByteArrayToHexString(data));
                    msgQueue.offer("COM3 receive:" + CommonUtils.ByteArrayToHexString(data));
                }
            });
            if(Com3.getInstance().isOpen())
            {
                ((Button)view).setText("关闭串口3");
            }
        }
    }

    public void openCom2(View view) {
        if(Com2.getInstance().isOpen())
        {
            Com2.getInstance().close();
            ((Button)view).setText("打开串口2");
        }
        else {
            Com2.getInstance().openSerialPort("/dev/ttys2", 9600, 0, new ReceiveMsgListenerV2() {
                @Override
                public void onReceiveData(byte[] data) {
                    Log.d(TAG, "COM2 receive:" + CommonUtils.ByteArrayToHexString(data));
                    msgQueue.offer("COM2 receive:" + CommonUtils.ByteArrayToHexString(data));
                }
            });
            if(Com2.getInstance().isOpen())
            {
                ((Button)view).setText("关闭串口2");
            }
        }
    }

    public void settingCom1(View view) {
        Com1.getInstance().setParams(38400,0);
    }

    public void settingCom2(View view) {
        Com2.getInstance().setParams(9600,0);
    }

    public void settingCom3(View view) {
        Com3.getInstance().setParams(38400,0);
    }

    public void settingCom4(View view) {
        Com4.getInstance().setParams(38400,0);
    }

    public void sendCom1(View view) {
        byte[] cmd  =   modbusUtil.read(1,new byte[]{0x0D,(byte)0xAC},new byte[]{0x00,0x01});
        byte[] cmd1  =   modbusUtil.read(1,new byte[]{0x0D,(byte)0xAC},new byte[]{0x00,0x64});
        Com1.getInstance().sendData(cmd1);
    }

    public void sendCom2(View view) {
        byte[] cmd = modbusUtil.read(2,new byte[]{0x00,0x01},new byte[]{0x00,0x01});
        byte[] com2Cmd1 = modbusUtil.read(2,new byte[]{0x00,0x10},new byte[]{0x00,0x60});
        Com2.getInstance().sendData(com2Cmd1);
    }

    public void sendCom3(View view) {
        byte[] cmd  =   modbusUtil.read(3,new byte[]{0x11,(byte)0xAA},new byte[]{0x00,0x01});
        Com3.getInstance().sendData(cmd);
    }

    public void sendCom4(View view) {
        byte[] cmd  =   modbusUtil.read(4,new byte[]{0x11,(byte)0xAA},new byte[]{0x00,0x01});
        Com4.getInstance().sendData(cmd);
    }

    public void sendCom5(View view) {
        Com5.getInstance().sendData(new byte[]{11,12,13,14,15,16});
    }

    private void hide()
    {
        Intent intentHideNotify = new Intent();
        intentHideNotify.setAction("lyzk.intent.systemui.hidestatusbar");
        intentHideNotify.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        this.sendBroadcast(intentHideNotify);

        Intent intentHideButton = new Intent();
        intentHideButton.setAction("lyzk.intent.systemui.hidenavigation");
        intentHideButton.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        this.sendBroadcast(intentHideButton);
    }
}